package com.juku2024.juku

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.adapter.DownloadFinishedAdapter
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.model.WatchEvent
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.WrapLinearLayoutManager
import com.juku2024.juku.viewmodel.DownloadViewModel
import com.juku2024.juku.widget.HeaderView
import com.juku2024.juku.widget.LoadingView
import com.wanban.download.WBDownloadUtils
import com.wanban.download.db.DownloadEntity
import com.wanban.download.model.Status
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class DownloadEpisodeListActivity : BaseActivity() {

    private lateinit var header: HeaderView
    private lateinit var btnAll: Button
    private lateinit var btnDelete: Button
    private lateinit var recyclerEpisodeList: RecyclerView
    private lateinit var loadingView: LoadingView
    private lateinit var editLayout: View

    private var videoId = 0L
    private val deleteList by lazy { ArrayList<DownloadEntity>() }
    private val downloadList by lazy { ArrayList<DownloadEntity>() }
    private val episodeAdapter by lazy { DownloadFinishedAdapter(ArrayList()) }
    private val viewModel by lazy { getViewModel(DownloadViewModel::class.java) }

    override fun getLayoutResId(): Int {
        return R.layout.activity_download_episode_list
    }

    override fun initView() {
        super.initView()
        header = findViewById(R.id.header_download_episode_list)
        btnAll = findViewById(R.id.btnAll_download_episode_list)
        btnDelete = findViewById(R.id.btnDelete_download_episode_list)
        editLayout = findViewById(R.id.editLayout)
        loadingView = findViewById(R.id.loadingView_download_episode_list)
        recyclerEpisodeList = findViewById(R.id.recyclerEpisodeList)


        videoId = intent?.getLongExtra(Constants.AROUTER_KEY_VIDEO_ID, 0L) ?: 0L
        val videoName = intent?.getStringExtra(Constants.AROUTER_KEY_VIDEO_NAME) ?: ""
        header.setTitle(videoName)
        recyclerEpisodeList.layoutManager = WrapLinearLayoutManager(this)
        recyclerEpisodeList.setHasFixedSize(true)
        recyclerEpisodeList.adapter = episodeAdapter
    }

    override fun bindEvent() {
        super.bindEvent()
        header.setOnEditClickListener {
            val isShowEditStatus = header.getMenuText() == getString(R.string.edit)
            changeEditUI(isShowEditStatus)
        }
        episodeAdapter.setOnItemClickListener { _, _, position ->
            val item = episodeAdapter.data[position]
            if (episodeAdapter.isShowCheck) {
                item.isSelected = !item.isSelected
                episodeAdapter.notifyItemChanged(position)
                modifySelectNum()
            } else {
                val intent = Intent(this, DownloadPlayerActivity::class.java)
                intent.putExtra(Constants.AROUTER_KEY_VIDEO_ID, item.videoId)
                intent.putExtra(Constants.AROUTER_KEY_DOWNLOAD_INDEX, item.episode)
                startActivity(intent)
            }
        }

        btnAll.setOnClickListener {
            val count = episodeAdapter.data.count { it.isSelected }
            if (count == episodeAdapter.data.size) {
                episodeAdapter.data.forEach { it.isSelected = false }
            } else {
                episodeAdapter.data.forEach { it.isSelected = true }
            }
            episodeAdapter.notifyDataSetChanged()
            modifySelectNum()
        }

        btnDelete.setOnClickListener {
            if (isActivityNotActive() || episodeAdapter.data.isEmpty()) return@setOnClickListener
            val deleteListTemp = episodeAdapter.data.filter { it.isSelected }
            if (deleteListTemp.isEmpty()) {
                return@setOnClickListener
            }
            deleteList.clear()
            deleteList.addAll(deleteListTemp)
            // https://hd.ijycnd.com/play/0dN78X6e/index.m3u8
            // https://hd.ijycnd.com/play/RdGw9z7d/index.m3u8
            showErrorDialog(
                "您确认删除选中的缓存内容吗？",
                getString(R.string.confirm), {
                    // 查询要删除的选项

                    WBDownloadUtils.deleteDownloads(deleteList) {

                    }

//                    deleteList.forEach {
//                        val deleteList = ArrayList<DownloadEntity>()
//                        it.state = Constants.APP_STATE_DELETE
//                        deleteList.add(it)
//                        EventBus.getDefault().post(DownloadEvent(deleteList))
//                        episodeAdapter.remove(it)
//                    }
//                    modifySelectNum()
//                    if (episodeAdapter.data.isEmpty()) {
//                        editLayout.visibility = View.GONE
//                        episodeAdapter.isShowCheck = false
//                        loadingView.showEmptyStatus(getString(R.string.dl_no_downloaded))
//                        header.setMenuText(getString(R.string.edit))
//                    }
                    hideErrorDialog()
                }, getString(R.string.cancel), {
                    hideErrorDialog()
                }
            )
        }
    }

    override fun init(savedInstanceState: Bundle?) {

    }

    override fun onResume() {
        super.onResume()
        loadingView.showLoading()
        viewModel.getDownloadFinishEpisodeList(videoId, {
            if (isActivityNotActive()) return@getDownloadFinishEpisodeList
            loadingView.hideLoading()
            downloadList.clear()
            downloadList.addAll(it)
            episodeAdapter.setList(it)
        }, {
            if (isActivityNotActive()) return@getDownloadFinishEpisodeList
            loadingView.hideLoading()
            loadingView.showEmptyStatus(getString(R.string.dl_no_downloaded))
        })
    }


    private fun modifySelectNum() {
        if (episodeAdapter.data.isEmpty()) {
            return
        }
        val count = episodeAdapter.data.count { it.isSelected }
        if (count != 0) {
            val text = if (count >= episodeAdapter.data.size) {
                getString(R.string.cancel_select_all)
            } else {
                getString(R.string.select_all)
            }
            btnAll.text = text
            btnDelete.setTextColor(AppUtils.getColor(R.color.color_text_light))
            btnDelete.text = String.format(AppUtils.getString(R.string.delete_num), count)
        } else {
            btnDelete.setTextColor(AppUtils.getColor(R.color.color_text_dark))
            btnDelete.text = String.format(AppUtils.getString(R.string.delete))
            btnAll.text = getString(R.string.select_all)
        }
    }

    private fun changeEditUI(isShowEditUI: Boolean){
        episodeAdapter.isShowCheck = isShowEditUI
        episodeAdapter.data.forEach { it.isSelected = false }
        episodeAdapter.notifyDataSetChanged()
        btnDelete.setTextColor(AppUtils.getColor(R.color.color_text_dark))
        btnDelete.text = String.format(AppUtils.getString(R.string.delete))
        btnAll.text = getString(R.string.select_all)
        editLayout.visibility = if (isShowEditUI) { View.VISIBLE } else { View.GONE }
        header.setMenuText(if (isShowEditUI) { getString(R.string.complete) } else { getString(R.string.edit) })
    }


    @Suppress("DEPRECATION")
    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (episodeAdapter.isShowCheck) {
            changeEditUI(false)
        } else {
            super.onBackPressed()
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDownloadEvent(event: DownloadEntity) {
        if (isActivityNotActive()) return
        doDownloadAdd(event)
    }

    private fun doDownloadAdd(task: DownloadEntity){
        // 只处理下载完成
        if (task.state != Status.SUCCESS) return
        // 只处理当前视频
        if (task.videoId != videoId) return
        episodeAdapter.addData(task)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDownloadVideoWatchedEvent(event: WatchEvent) {
        if (isActivityNotActive()) return
//        episodeAdapter.data[event.position].playProgress = event.watchTime
//        episodeAdapter.notifyItemChanged(event.position)
    }
}